import ExamStatus from '@/components/type-of-exam/types/exam-status';
import { QuestDefaultApi } from '@/library/util/api';
import { swapArray } from '@/library/util/array';
import { defaultErrorHandler } from '@/library/util/error-handler';
import { message } from 'ant-design-vue';
import _ from 'lodash';
import { defineStore } from 'pinia';
import { useLoginInforStore } from '../login';
import ContentAdapter from './adpater/ContentAdapter';
import { Blank, Choose, ExamItem, Questionaire, QuestsType } from './types';

interface DesignContentState {
  /** 问卷信息 */
  questionaire: Questionaire;

  /** 题目信息 */
  content: ExamItem[];
}
export const useDesignContentStore = defineStore({
  id: 'DesignContentStore',
  state: (): DesignContentState => ({
    questionaire: new Questionaire(),
    content: [],
  }),
  getters: {
    /**
     * 获取题列表
     */
    getContentList(): ExamItem[] {
      return this.content;
    },

    /**
     * 获取问卷信息
     * @returns
     */
    getQuestionaire(): Questionaire {
      return this.questionaire;
    },
  },
  actions: {
    /**
     * 创建问卷
     */
    async queryCreate() {
      try {
        const userStore = useLoginInforStore();
        const params = {
          ...new ContentAdapter().parse(
            this.questionaire,
            this.content,
            userStore.getUserInfo.userId,
          ),
        };

        await QuestDefaultApi.questionaireCreateQuestionairePost(params);
        message.success('问卷新建成功');
      } catch (error) {
        defaultErrorHandler(error);
      }
    },

    /**
     * 添加小题
     * @param value ExamItem
     */
    addExam(value: QuestsType) {
      // TODO 区分题型
      const vo = new ExamItem(
        value.id,
        value.typeName,
        false,
        this.getContentList.length + 1,
      );

      if (value.id === 2 || value.id === 3 || value.id === 4) {
        // 单选
        const first = new Choose('选项A', 0);
        const second = new Choose('选项B', 1);
        const temp: Choose[] = [];
        temp.push(first, second);
        vo.options = temp;
      } else if (value.id === 6) {
        // 填空的初始化
        vo.blanks = new Array(1).fill(new Blank());
      }

      this.content.push(vo);
    },

    /**
     * 清空
     */
    clearExam() {
      this.content = [];
    },

    /**
     * 变更状态至编辑
     * @param value ExamItem
     */
    changeStatus(value: ExamItem) {
      this.content.forEach((item) => {
        if (item.questNum === value.questNum) {
          if (item.status === 'basic') {
            item.status = ExamStatus.Edit;
          } else {
            item.status = ExamStatus.Basic;
          }
        } else {
          item.status = ExamStatus.Basic;
        }
      });
    },

    /**
     * 设置题
     * @param value
     */
    setContent(value: ExamItem[]) {
      this.content = value;
    },

    /**
     * 复制题
     * @param value
     */
    copyExam(value: ExamItem) {
      const newExam: ExamItem = _.cloneDeep(value);
      newExam.status = ExamStatus.Basic;
      this.content.splice(value.questNum, 0, newExam);
      for (let i = value.questNum; i < this.content.length; i++) {
        if (i > 0 && this.content[i].questNum >= this.content[i - 1].questNum) {
          this.content[i].questNum++;
        }
      }
    },

    /**
     * 删除题
     * @param value
     */
    deleteExam(value: ExamItem) {
      this.content.splice(value.questNum - 1, 1);

      for (let i = value.questNum; i < this.content.length; i++) {
        this.content[i].questNum--;
      }
    },

    /**
     * 上移
     * @param value
     */
    moveUpExam(value: ExamItem) {
      try {
        if (value.questNum === 1) {
          throw new Error('第1题不能再上移');
        }
        swapArray(this.content, value.questNum - 2, value.questNum - 1);

        // 上移之后题号重排
        this.remakeNum();
      } catch (error) {
        defaultErrorHandler(error);
      }
    },

    /**
     * 下移
     * @param value
     */
    moveDownExam(value: ExamItem) {
      try {
        if (value.questNum === this.content.length) {
          throw new Error('最后1题不能再下移');
        }
        swapArray(this.content, value.questNum - 1, value.questNum);
        this.remakeNum();
      } catch (error) {
        defaultErrorHandler(error);
      }
    },

    moveTopExam(value: ExamItem) {
      try {
        if (value.questNum === 1) {
          throw new Error('第1题不能再上移');
        }
        this.content.unshift(this.content.splice(value.questNum - 1, 1)[0]);
        this.remakeNum();
      } catch (error) {
        defaultErrorHandler(error);
      }
    },

    moveBottomExam(value: ExamItem) {
      try {
        if (value.questNum === this.content.length) {
          throw new Error('最后1题不能再下移');
        }
        this.content.push(this.content.splice(value.questNum - 1, 1)[0]);
        this.remakeNum();
      } catch (error) {
        defaultErrorHandler(error);
      }
    },

    /**
     * 题号重排
     */
    remakeNum() {
      this.content.map((item, index) => (item.questNum = index + 1));
    },

    setQuestionaire(value: Questionaire) {
      this.questionaire = value;
    },

    reSet() {
      this.content = [];
      this.questionaire = new Questionaire();
    },

    setTitle(value: string | undefined) {
      if (!value) value = '默认标题';
      this.questionaire.queTitle = value;
    },
  },
});
